package com.ym.pms.security.handler;

import com.alibaba.fastjson.JSON;
import com.ym.pms.security.config.JWTConfig;
import com.ym.pms.utils.JSONResult;
import com.ym.pms.security.utils.JWTTokenUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: xybh
 * @Description:
 * @Date: Created in 11:23 2020/12/21
 * @Modified:
 */
@Component
@Slf4j
public class UserLogoutSuccessHandler implements LogoutSuccessHandler {

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        String token = httpServletRequest.getHeader(JWTConfig.tokenHeader);
        JWTTokenUtil.addBlackList(token);

        log.info("用户{}登出成功, Token信息已保存到Redis的黑名单中", JWTTokenUtil.getUserNameByToken(token));
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().println(JSON.toJSONString(JSONResult.build(200, "登出成功", null)));
    }
}
